<?php


namespace App\Http\Controllers\Admin\Game;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use App\Response\Response;
use Illuminate\Support\Facades\DB;
use mysql_xdevapi\Exception;

class GameConfigController extends BaseController
{

    //获取卡位赔率等配置信息
    /**
     * @api {get} /guessing/config 获取卡位赔率等配置信息
     * @apiVersion 0.1.0
     * @apiName 获取卡位赔率等配置信息
     * @apiGroup 霍克城堡 竞猜
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "id": 1,
     * "odds": 80,
     * "output_limit": 0,
     * "history_output_limit": 0,
     * "notice_count": 9000,
     * "is_open": 1,
     * "slots": [
     * {
     * "index": 1,
     * "times": 15
     * },
     * {
     * "index": 2,
     * "times": 10
     * },
     * {
     * "index": 3,
     * "times": 10
     * },
     * {
     * "index": 4,
     * "times": 7
     * },
     * {
     * "index": 5,
     * "times": 7
     * },
     * {
     * "index": 6,
     * "times": 7
     * },
     * {
     * "index": 7,
     * "times": 4
     * },
     * {
     * "index": 8,
     * "times": 4
     * }
     * ],
     * "created_at": "2021-07-30 13:07:45.149474",
     * "updated_at": "2021-07-30 13:07:45" //修改时间
     * }
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function getconfig(Request $request)
    {
        $data = app('model_game_config')->where('id', 1)->first();
        if (empty($data)) {
            throw  new BasicException(10001, '数据错误请联系技术人员');
        }
        $data = $data->toArray();
        $data['slots'] = json_decode($data['slots']);
        $data['updated_at'] = substr($data['updated_at'], 0, 19);

        return Response::sendData($data);
    }

    //编辑各个卡位赔率

    /**
     * @api {put} /guessing/config/slots 编辑各个卡位赔率
     * @apiVersion 0.1.0
     * @apiName 编辑各个卡位赔率
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {String}                     slots_config 各个卡位赔率 用","分隔（必填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function editConfig(Request $request)
    {
        $configdate = $request->input('slots_config');
        $configdate = explode(',', $configdate);
        if (count($configdate) != 8) {
            throw  new BasicException(10001, '卡位数量错误');
        }
        foreach ($configdate as $v) {
            if (!is_numeric($v) || abs(floor($v)) != $v) {
                throw  new BasicException(10001, '赔率配置为正数');
            }
        }
        $slots = [];
        foreach ($configdate as $key => $v) {
            $slots[] = [
                'index' => $key + 1,
                'times' => $v,
            ];
        }
        $slots = json_encode($slots);
        $res = app('model_game_config')->where('id', 1)->update(['slots' => $slots]);
        if ($res) {
            return Response::sendData(true);
        } else {
            throw  new BasicException(10001, '没有做修改');
        }
    }

    //修改玩法配置

    /**
     * @api {put} /guessing/config/playconfig 修改玩法配置
     * @apiVersion 0.1.0
     * @apiName 编辑各个卡位赔率
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     output_limit 产出限制 （必填）
     * @apiParam {Int}                     history_output_limit 历史产出限制 （必填）
     * @apiParam {Int}                     odds 实际赔率为（必填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function editPlayConfig(Request $request)
    {
        $data = $request->only(['output_limit', 'history_output_limit', 'odds']);
        $va = app('validator')->make($data, [
            'output_limit'         => 'required|integer',//产出限制
            'history_output_limit' => 'required|integer',//历史产出限制
            'odds'                 => 'required|numeric|min:0|max:10',//赔率
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $data['odds'] = $data['odds'] * 100;
        $res = app('model_game_config')->where('id', 1)->update($data);
        if ($res) {
            return Response::sendData(true);
        } else {
            throw  new BasicException(10001);
        }
    }

    //数据看板

    /**
     * @api {get} /guessing  数据看板
     * @apiVersion 0.1.0
     * @apiName 数据看板
     * @apiGroup 霍克城堡 竞猜
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "card2": {
     * "join_num": 121//参与人数
     * },
     * "card3": {
     * "user_round_max_input": "7510",// 单个用户最大投入||一场竞猜下的下注最多
     * "round_sum_input": "225948"//总投入
     * },
     * "card4": {
     * "user_round_max_onput": 14985,//单个用户最大支出||一场竞猜下的获利最多
     * "round_sum_output": "225948"//总支出
     * },
     * "card5": {
     * "history_round_max_input": 2023807,//历史单场最大投入
     * "histroy_round_input": "14002973023"       //  历史总投入
     * },
     * "card6": {
     * "history_round_max_output": 4089015,//历史单场最大支出
     * "histroy_round_output": "3561620052"//历史总支出
     * }
     * }
     * }
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function endRound(Request $request)
    {
        //上次配置下的 人均游戏次数,参与占比

        //拿上次配置信息
        $lastConfig = app('model_game_config_log')
            ->orderBy('created_at', 'desc')
            ->first()
            ->toArray();

        //        人均游戏次数=上次配置下的总游戏次数/参与人数


        //        参与占比=本场用户总参与次数/总人数
        //参与人数||本场用户总参与次数
        $joinNum = app('model_game_bet')->where('round_id', '>', $lastConfig['round_id'])->groupBy('user_id')->count();

        //         单个用户最大投入||一场竞猜下的下注最多
        $userRoundMaxinput = DB::connection('mysql_game')->select('SELECT MAX(suminput) FROM (SELECT SUM(input) AS suminput FROM bet  WHERE round_id>' . $lastConfig['round_id'] . ' GROUP BY round_id,user_id) AS a');
        $userRoundMaxinput = array_map(function ($value) {
            return (array)$value;
        }, $userRoundMaxinput);
        $userRoundMaxinput = $userRoundMaxinput[0]['MAX(suminput)'];

        //        总投入
        $RoundSumInput = app('model_game_bet')->where('round_id', '>', $lastConfig['round_id'])->sum('input');

        //        单个用户最大支出||一场竞猜下的获利最多
        $userRoundMaxpOutput = app('model_game_bet')->where('round_id', '>', $lastConfig['round_id'])->max('output');
        //        总支出
        $userRoundSumOutput = app('model_game_bet')->where('round_id', '>', $lastConfig['round_id'])->sum('input');

        //      历史单场最大投入
        $historyRoundMaxInput = app('model_game_round')->max('input');
        //  历史总投入
        $historyRoundSumInput = app('model_game_round')->sum('input');

        //      历史单场最大支出
        $historyRoundMaxOutput = app('model_game_round')->max('output');
        //  历史总支出
        $historyRoundSumOutput = app('model_game_round')->sum('output');

        $res = [
            'card2' => ['join_num' => $joinNum],
            'card3' => ['user_round_max_input' => $userRoundMaxinput, 'round_sum_input' => $RoundSumInput],
            'card4' => ['user_round_max_onput' => $userRoundMaxpOutput, 'round_sum_output' => $userRoundSumOutput],
            'card5' => ['history_round_max_input' => $historyRoundMaxInput, 'histroy_round_input' => $historyRoundSumInput],
            'card6' => ['history_round_max_output' => $historyRoundMaxOutput, 'histroy_round_output' => $historyRoundSumOutput],
        ];

        return Response::sendData($res);
    }

}

